/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package slowniki.dao;

import commons.AbstractDAO;
import commons.DbConnection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import slowniki.data.Kraj;

/**
 *
 * @author mbudzilo
 */
public class KrajDAO extends AbstractDAO {

    public KrajDAO() {
        conn = DbConnection.getConnection();
    }

    public ArrayList<Kraj> getKrajList() {
        ArrayList<Kraj> list = new ArrayList<Kraj>();


        try {
            String query = "kra_id, "
                    + "kra_nazwa "
                    + "from kraj order by nazwa";

            prepStmt = conn.prepareStatement(query);
            //prepStmt.setString(1, s+"%");
            rs = prepStmt.executeQuery();

            while (rs.next()) {
                Kraj data = new Kraj();
                data.setId(rs.getInt(1));
                data.setNazwa(rs.getString(2));
                list.add(data);

            }
            return list;

        } catch (SQLException ex) {
            error(ex.getMessage());
            Logger.getLogger(KrajDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

    public void insertKraj(Kraj kraj) {
        try {
            String query = "insert into kraj(kra_nazwa) values (?)";

            prepStmt = conn.prepareStatement(query);
            prepStmt.setString(1, kraj.getNazwa());
            int ile = prepStmt.executeUpdate();
            if (ile == 0) {
                error("Nie udało się dodać kraju.");
            }
        } catch (SQLException ex) {
            error(ex.getMessage());
            Logger.getLogger(KrajDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void deleteKraj(Kraj kraj) {
        try {
            String query = "delete from kraj where kra_id = ?";

            prepStmt = conn.prepareStatement(query);
            prepStmt.setInt(1, kraj.getId());
            int ile = prepStmt.executeUpdate();
            if (ile == 0) {
                error("Nie udało się usunąć kraju.");
            }
        } catch (SQLException ex) {
            error(ex.getMessage());
            Logger.getLogger(KrajDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void updateKraj(Kraj kraj) {

        try {
            String query ="update kraj set kra_nazwa =? where kra_id = ?";

            prepStmt = conn.prepareStatement(query);
            prepStmt.setString(1, kraj.getNazwa());
            prepStmt.setInt(2, kraj.getId());
            rs = prepStmt.executeQuery();

        } catch (SQLException ex) {
            error(ex.getMessage());
            Logger.getLogger(KrajDAO.class.getName()).log(Level.SEVERE, null, ex);
        }


    }
}
